package csu.jpetstore.jpetstore.config.security;

import csu.jpetstore.jpetstore.domain.AdminUserRole;
import csu.jpetstore.jpetstore.domain.UserAuths;
import csu.jpetstore.jpetstore.domain.Users;
import csu.jpetstore.jpetstore.service.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ProjectRealm extends AuthorizingRealm {
    @Autowired
    private UserAuthsService userAuthsService;

    @Autowired
    private NormalUsersService normalUsersService;

    @Autowired
    private AdminPermissionService adminPermissionService;

    @Autowired
    private AdminUserRoleService adminUserRoleService;

    @Autowired
    private AdminRoleService adminRoleService;

    // 简单重写获取授权信息方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userId = principals.getPrimaryPrincipal().toString();
        Set<String> permissions = new HashSet<>(adminPermissionService.getPermissionsUrlAndMethod(userId));
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        s.setStringPermissions(permissions);
        List<Integer> roleId = adminUserRoleService.getRoleIdByUserId(userId);
        s.setRoles(new HashSet<>(adminRoleService.getRoles(roleId)));
        return s;

    }

    // 获取认证信息，即根据 token 中的用户名从数据库中获取密码、盐等并返回
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userId = token.getPrincipal().toString();
        Users user = normalUsersService.findByUserId(userId);
        UserAuths userAuths = userAuthsService.getByUser(user);

        String passwordDB = userAuths.getPassword();
        String salt = userAuths.getSalt();
        return new SimpleAuthenticationInfo(userId,passwordDB, ByteSource.Util.bytes(salt), getName());
    }
}
